package com.atguigu.gmall.product.service.impl;

import com.atguigu.gmall.common.config.minio.properties.MinioProperties;
import com.atguigu.gmall.common.util.DateUtil;
import com.atguigu.gmall.product.service.FileService;
import io.minio.MinioClient;

import io.minio.PutObjectOptions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.InputStream;
import java.util.Date;
import java.util.UUID;

@Service
public class FileServiceImpl implements FileService {
    @Autowired
    MinioProperties  minioProperties;
    @Autowired
    MinioClient  minioClient;
    @Override
    public String upload(MultipartFile file) throws Exception {
     //创建MinioClient 和判断Bucket 已经封装好了
        //3上传文件 ，加上唯一前缀
        String date= DateUtil.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss");
        String filename=date+"/"+ UUID.randomUUID().toString()+"_"+file.getOriginalFilename();
        InputStream stream = file.getInputStream();
        PutObjectOptions options =new PutObjectOptions(file.getSize(),-1L);
        options.setContentType(file.getContentType());//文件上传类型
        //上传
        minioClient.putObject(minioProperties.getBucketName(),filename,stream,options);
        //返回文件访问路径
        String url=minioProperties.getEndpoint()+"/"+minioProperties.getBucketName()+"/"+filename;

        return url;
    }
}
